<script setup lang="ts">
  import { ref, onBeforeMount } from 'vue';
  import { queryDeviceAlarmOrderList } from '@/api/workorder-management/alarm';
  import InnerPage from '@/components/inner-page/index.vue';
  import * as Lodash from 'lodash';
  import OrderDetails from './details.vue';

  const loading = ref(false);
  const baseNameMap = {
    itemId: { key: 'orderId', label: '' },
    itemEventName: {
      key: 'eventName',
      label: '事件名称',
      placeholder: '请输入报警事件名称',
    },
    itemStatus: {
      key: 'status',
      label: '工单状态',
      placeholder: '请选择工单状态',
    },
    btnAction: { label: '操作' },
    btnLook: { label: '查看' },
  };

  const dataPage = ref({
    total: 0,
    page: 1,
    pageSize: 6,
  });

  const itemStatusOptions = [
    { label: '待接单', value: 1 },
    { label: '已接单', value: 2 },
    { label: '已完结', value: 3 },
  ];

  const alarmOrders = ref<any[]>([]);

  const getOrderDescription = (item: any) => {
    let desc = '';
    if (item.status === 1) {
      desc = `${item.createdAt}发起报警，已等待`;
    } else if (item.status === 2) {
      desc = `${item.assignedAt}接收工单，已用时`;
    } else if (item.status === 3) {
      desc = `${item.closedAt}完结工单，总用时`;
    }
    return desc;
  };
  const getOrderTimeUse = (item: any) => {
    let startTime = '';
    let endTime = new Date();
    if (item.status === 1) {
      startTime = item.createdAt;
    } else if (item.status === 2) {
      startTime = item.assignedAt;
    } else if (item.status === 3) {
      startTime = item.createdAt;
      endTime = new Date(item.closedAt);
    } else {
      return '-';
    }
    const startTimestamp = new Date(startTime).getTime();
    const endTimestamp = endTime.getTime();
    let seconds = Lodash.parseInt(`${(endTimestamp - startTimestamp) / 1000}`);
    let desc = '';
    const hours = seconds / 3600;
    if (hours > 0) {
      const tH = parseInt(hours.toString(), 10);
      seconds -= tH * 3600;
      desc += `${tH}小时`;
    }
    const minutes = seconds / 60;
    if (minutes > 0) {
      const tM = parseInt(minutes.toString(), 10);
      seconds -= tM * 60;
      desc += `${tM}分`;
    }
    if (seconds > 0) {
      desc += `${seconds}秒`;
    }
    return desc;
  };

  const searchForm = ref({
    state: {
      [baseNameMap.itemEventName.key]: '',
      [baseNameMap.itemStatus.key]: '',
    },
    search: (reset = false) => {
      loading.value = true;
      if (reset) {
        dataPage.value.page = 1;
      }
      const params = {
        ...dataPage.value,
        eventName: searchForm.value.state[
          baseNameMap.itemEventName.key
        ] as string,
        status: searchForm.value.state[baseNameMap.itemStatus.key] as string,
      };
      queryDeviceAlarmOrderList(params)
        .then((res) => {
          dataPage.value.total = res.total;
          alarmOrders.value = res.list;
          // console.log(res.list);
        })
        .finally(() => {
          loading.value = false;
        });
    },
  });

  const infoHandler = ref({
    props: {
      [baseNameMap.itemId.key]: '',
    },
    onBack: () => {
      infoHandler.value.props[baseNameMap.itemId.key] = '';
      searchForm.value.search(true);
    },
  });

  const onPageChange = (current: number) => {
    dataPage.value.page = current;
    searchForm.value.search();
  };

  onBeforeMount(() => {
    searchForm.value.search(true);
  });
</script>

<template>
  <div class="m-alarm flex-col">
    <div class="m-alarm-raw">
      <div class="m-ar-search flex-vcenter" style="padding: 0 6px">
        <a-form
          :model="searchForm.state"
          layout="inline"
          @submit="() => searchForm.search(true)"
        >
          <!-- 事件名称 -->
          <a-form-item
            :field="baseNameMap.itemEventName.key"
            :label="baseNameMap.itemEventName.label"
          >
            <a-input
              v-model="searchForm.state[baseNameMap.itemEventName.key]"
              :placeholder="baseNameMap.itemEventName.placeholder"
              allow-clear
            />
          </a-form-item>
          <!-- 工单状态 -->
          <a-form-item
            :field="baseNameMap.itemStatus.key"
            :label="baseNameMap.itemStatus.label"
          >
            <a-select
              v-model="searchForm.state[baseNameMap.itemStatus.key]"
              :placeholder="baseNameMap.itemStatus.placeholder"
              allow-clear
            >
              <a-option
                v-for="(item, index) of itemStatusOptions"
                :key="'itemStatus-' + index"
                :value="item.value"
                :label="item.label"
              />
            </a-select>
          </a-form-item>
        </a-form>
        <a-button
          type="primary"
          :loading="loading"
          @click="() => searchForm.search(true)"
          >查询</a-button
        >
      </div>
      <a-divider />
    </div>
    <div class="m-alarm-body flex-1 flex-col">
      <a-card class="m-ab-content" :bordered="false">
        <a-card-grid
          v-for="(item, index) of alarmOrders"
          :key="'alarmOrder-' + index"
          hoverable
          :col-gap="20"
          style="width: 49%; cursor: pointer"
        >
          <a-card class="m-abc-item" hoverable :bordered="false">
            <template #title>
              <div
                class="flex-vcenter"
                style="padding-right: 20px; font-size: 15px"
              >
                <span class="m-abci-title">{{ item.eventName }}</span>
                <span class="flex-1"></span>
                <span v-if="item.status === 1" class="title-status-will"
                  >待接单</span
                >
                <span v-else-if="item.status === 2" class="title-status-doing"
                  >已接单</span
                >
                <span v-else-if="item.status === 3" class="title-status-done"
                  >已完结</span
                >
              </div>
            </template>
            <div class="m-abci-content flex">
              <span>
                <a-image height="64" width="64" :src="item.deviceImageUrl" />
              </span>
              <span
                class="flex-1 flex-col"
                style="padding: 0 8px; row-gap: 2px"
              >
                <div style="font-weight: 600">
                  <span>{{ item.elderName }}</span>
                  <span style="margin: 0 8px">{{ item.elderGender }}</span>
                  <span>{{ item.elderAge }}岁</span>
                </div>
                <div>
                  <span>{{ item.installFullAddress }}</span>
                </div>
                <div>
                  <span style="margin-right: 4px">{{
                    getOrderDescription(item)
                  }}</span>
                  <span
                    :style="{
                      color: item.status !== 3 ? 'rgb(var(--orange-6))' : '',
                    }"
                    >{{ getOrderTimeUse(item) }}</span
                  >
                </div>
              </span>
              <span class="flex-col">
                <span class="flex-1"></span>
                <!-- <a-button
                  type="primary"
                  size="mini"
                  @click="
                    infoHandler.props[baseNameMap.itemId.key] = item.orderNo
                  "
                  >查看</a-button
                > -->
              </span>
            </div>
          </a-card>
        </a-card-grid>
      </a-card>
      <a-pagination
        v-model:current="dataPage.page"
        class="flex"
        style="margin-top: 15px; flex-direction: row-reverse"
        :total="dataPage.total"
        :page-size="dataPage.pageSize"
        @change="onPageChange"
      />
    </div>
    <!-- <Transition name="slide-right"> -->
    <InnerPage
      v-if="infoHandler.props[baseNameMap.itemId.key]"
      class="m-alarm-details"
      @back="infoHandler.onBack"
    >
      <!-- 工单详情 -->
      <OrderDetails v-bind="infoHandler.props" />
    </InnerPage>
    <!-- </Transition> -->
  </div>
</template>

<style lang="less" scoped>
  .m-alarm {
    height: 100%;
    max-width: 100%;
    overflow: hidden;
  }

  .m-alarm-body {
    .m-ab-content {
      padding-top: 10px;

      .m-abc-item {
        .m-abci-title {
          display: inline-block;
          font-weight: 600;
          width: 200px;
          background-color: rgb(var(--arcoblue-1));
          border-bottom-right-radius: 12px;
          padding: 2px 12px;
          box-sizing: border-box;
        }

        .title-status-will {
          color: rgb(var(--orange-6));
        }

        .title-status-doing {
          color: rgb(var(--green-6));
        }

        .title-status-done {
        }

        .m-abci-content {
          padding: 10px 17px;
        }
      }
    }
  }

  .m-alarm-body :deep(.arco-card-body) {
    padding: 0 4px;
    justify-content: space-between;
    row-gap: 20px;
    max-height: 100%;

    .arco-card-grid {
      // height: 24%;
      border-radius: 4px;
      // overflow: hidden;
    }
  }
  .m-alarm-body :deep(.arco-card-header) {
    border: none;
    padding: 0;
    height: unset;
  }
</style>
